package com.oocl.command.executor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.oocl.command.Command;
import com.oocl.exception.MyException;

public class CommandExecutorImpl  implements CommandExecutor{

	public void sovleCommand(BufferedReader reader, OutputStream out, Command cmd) throws MyException, IOException {
		// TODO Auto-generated method stub
		switch(cmd.getOperationType()){
		case "scp":{
			uploadData(reader,out,cmd.getValues());
			break;
			
		}
		case "ls":{
			listFileNames(reader,out);
			break;
			
		}
		case "rm":{
			removeFile(reader,out,cmd.getValues());
			break;
			
		}
		default:break;
		}
	}
	
	
	
	
	
	private void removeFile(BufferedReader reader,OutputStream out,String[] values) throws IOException {
		// TODO Auto-generated method stub
		out.write("rm\n".getBytes());
		out.write((values[0]+"\n").getBytes());
		String  s = reader.readLine();
		if("200".equals(s)){
			System.out.println("delete sucess");
		}else{
			System.out.println(s);
		}
	}





	private void listFileNames(BufferedReader reader,OutputStream out) throws IOException {
		// TODO Auto-generated method stub
		out.write("ls\n".getBytes());
		while(true){
			String s = reader.readLine();
			if("200".equals(s)){
				break;
			}
			System.out.println(s);
		}
	}



	private void uploadData(BufferedReader reader, OutputStream out, String[] value) throws MyException, IOException{
		String fileName = value[0];
		String[] strs1 = fileName.split("/");
		String[] strs = value[1].split(":");
		String path = "upload/";
		if(strs.length>1){
			
			path = strs[1]+":"+strs[2];
		}
		InputStream in1;
		try {
			 in1 = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			throw new MyException("001","FileNotFoundException","FileNotFoundException");
		}
		out.write("scp\n".getBytes());
		String file =path+strs1[strs1.length-1]+"\n";
		out.write(file.getBytes());
		String status = reader.readLine();
		if("200".equals(status)){
			int len = 0;
			byte[] bs = new byte[100];
			while((len=in1.read(bs))!=-1){
				out.write(bs,0,len);
			}
		}
		String status1 = reader.readLine();
		if("200".equals(status1)){
			System.out.println("upload success");
		}
		
	}

}
